package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.AnnounceDao;
import dao.impl.AnnounceDaoImpl;
import model.Announces;
import model.User;

/**
 * Servlet implementation class PostServlet
 */
@WebServlet("/PostServlet")
public class PostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PostServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		String topic = request.getParameter("topic");
		String content = request.getParameter("body");
		String style = request.getParameter("style");
		String score = request.getParameter("topic[point]");
		//设置帖子类型
		long classId ;
		switch (style) {
		case "音乐":
			classId = 1 ;
		case "阅读":
			classId = 3 ;
		case "电影":
			classId = 2 ;
		default:
			classId = 4 ;
			break;
		}
		//得到用户信息
		User user = (User) request.getSession().getAttribute("logoner");
		Announces ann = new Announces();
		ann.setAnnTopic(topic);
		ann.setAnnBody(content);
		ann.setClassID(classId);
		ann.setAnnTime(new Date());
		ann.setUserID(user.getUserId());
		ann.setAnnRacc(Integer.parseInt(score));
		AnnounceDao ad = new AnnounceDaoImpl();
		try {
			if(ad.insertAnn(ann) && ad.updateUserAnnCount(ann)) {
				response.sendRedirect("IndexServlet");
			}else {
				response.sendRedirect("pages/post.jsp");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
